//
//  CNViewController.m
//  chuiniu
//
//  Created by zheng ji on 14-7-22.
//  Copyright (c) 2014年 jxw. All rights reserved.
//
#define  diceBodyWidth 60 //盒子宽度
#define  diceBodyHeight 67 //盒子高度
#define Dice_Width 45 //骰子宽度
#define Dice_Height 45 //骰子高度
#define Desk_Height 310//游戏桌子高度
#define Desk_Width 480 //游戏桌子宽度
#define TAG_PhoneDiceBody 5001//手机骰子盒子tag
#define TAG_PhoneDiceTo 5002//手机骰子底盘tag
#define TAG_PlayerDiceBody 5003//玩家骰子盒子tag

#define BaseTag_PhoneDice 600  //手机骰子tag
#define BaseTag_SelectDice 100  //供选择骰子起始tag

#define Select_Dice_Width 30 //供选择的骰子宽度
#define Select_Dice_Height 30 //供选择的骰子高度



#import "CNViewController.h"
#import "CNIntroduceViewController.h"

#import "CNPlayer.h"
#import "CNAppDelegate.h"
#import "CNGameUtil.h"
#import "CNGameClient.h"
#import "CNOnlinePlayerController.h"
@interface CNViewController ()
{
    CNAppDelegate* _appDelegate;
    CNGameClient* _gameClient;
    
    CGFloat _startY;
    CNScoreView* _scoreView;
    UIImageView *_image1;
    UIImageView *_image2;
    UIImageView *_image3;
    UIImageView *_image4;
    UIImageView *_image5;
    
    UIImageView *_dong1,*_dong2,*_dong3,*_dong4,*_dong5;
    
    UITextField* _textFieldCount;
    BOOL isOpened;
    NSMutableArray* _arrayPlayerNumber;//玩家骰子数字
    NSMutableArray* _arrayPhoneNumber;//手机骰子数字
    
    UITableView* _tableCountNumber;//总数表
    NSArray *_countNumberArray;//可选数组
    UIView* _viewCount;//
    CNGuestView* _phoneGuestView;//手机猜测结果显示
    CNGuestView* _playerGuestView;//手机猜测结果显示
    int _playerSelectedNumber;//玩家选中的数字
    
    
    BOOL _blHasGuess;//是否已经猜数字
    
    //BOOL _blCurrentGuess;//false:玩家猜测，true:手机猜测
    int _whoCurrentGuess;//0: 当前结果是用户猜测，1：当前结果是手机猜测
    int _currentGuessAmount;// 当前猜测的总数
    int _currentGuessNumber;//当前猜测的数字
       BOOL _blGuessOne;//是否已经猜测了1，则1不具备万能功能
    
    int _whoOpened;//0: 玩家开得，1： 手机开的
    
    int _phoneWinCount,_phoneFailureCount;//手机输赢统计
    int _playerWinCount,_playerFailureCount;// 玩家输赢统计
    
    NSUserDefaults* _userDefaults;
    
    UILabel* _lblPlayer;
    UILabel* _lblShouJi;
    
    NSTimer* _timer;
    UILabel* _lblTimeCount;
    
    int _intBottomSpace;
   
    CNPlayer* _player;//玩家名称
    CNPlayer* _vsPlayer;//对家名称
    
    BOOL  isPlayingVS;//玩家是否正在对战
    iToast *toast;
    int _chipCoins;//每局的筹码，默认50个金币
    
   BOOL _isPlayerGuess;//是否轮到玩家猜测
   BOOL _isShaked;// 是否已经摇定骰子
    
}
@end

@implementation CNViewController

/*初始化总数表*/
-(void)initCountNumberTable:(CGRect)frame{
    _countNumberArray=[NSArray arrayWithObjects:@"  1",@"  2",@"  3",@"  4",@"  5",@"  6",@"  7",@"  8",@"  9",@" 10", nil];
    _tableCountNumber=[[UITableView alloc]initWithFrame:frame style:UITableViewStylePlain];
    _tableCountNumber.delegate=self;
    _tableCountNumber.dataSource=self;
    [_tableCountNumber registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse_themeCell"];
    [self.view addSubview:_tableCountNumber];
}
//开猜测结果
-(void)openPhoneDiceBody:(UIGestureRecognizer*)gestrue{
    
    
    
    if(!_isShaked){
        [CommonConfigUtil showToast:kToastPositionCenter withTitle:@"请轻点己方的骰蛊摇动骰子！"];
        return;
    }
    
    
    if(!_isPlayerGuess){
        [CommonConfigUtil showToast:kToastPositionCenter withTitle:@"请等待对家猜测！"];
        
        return ;
    }

    if(_whoCurrentGuess==0){
        //自己猜测的不能开
        [CommonConfigUtil showToast:kToastPositionCenter withTitle:@"当前是您猜测的结果，不能开看！"];
        
        return ;
    }
    if(_gameModel==GameModelMutilPlayer){
        [self openGuessMutilPlay:PlayerOpened];
    }else{
        if(!_blHasGuess){
            [CommonConfigUtil showToast:kToastPositionCenter withTitle:@"请先猜测骰子！"];
            
            return ;
        }
      UIImageView* diceBodyView=(UIImageView*)gestrue.view;
      _whoOpened=0;//
      [self openGuess:diceBodyView];
    }
}

//显示手机的骰子
-(void)showPhoneDice:(UIImageView*)diceBodyView{
    [self stopCountDown];//停止倒计时
    
        //UIImageView* diceBodyView=(UIImageView*)gestrue.view;
    
    int axisX=self.view.frame.size.width /2  - Dice_Width * 5 /2;
    int axisY=diceBodyView.frame.origin.y + diceBodyView.frame.size.height;
    int tag=BaseTag_PhoneDice;
    for (NSString* strNum in _arrayPhoneNumber) {
        
        UIImageView* view1=[[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@@2x.png",strNum]]];
        tag= tag +1;
        view1.tag= tag;
        view1.frame=CGRectMake(axisX,axisY,Dice_Width,Dice_Height);
        [self.view addSubview:view1];
        
        axisX=axisX + Dice_Width +2;
    }
    diceBodyView.image=[UIImage imageNamed:@"diceto.png"];
    
    UIImageView* diceToView=(UIImageView*)[self.view viewWithTag:TAG_PhoneDiceTo];
    diceToView.image=[UIImage imageNamed:@"dicebody.png"];
    diceToView.hidden=NO;
    isOpened=YES;

}

//统计当前猜测点数的骰子总数量
-(int)countCurrentGuessNumber{
    int count=0;
    NSString* strCurrentNumber=[NSString stringWithFormat:@"%d",_currentGuessNumber];
    
    for (NSString* str in _arrayPhoneNumber) {
        
        if([str isEqualToString:strCurrentNumber]){
            count ++;
        }else if([str isEqualToString:@"1"] && !_blGuessOne){
            //1 具备万能效果
            count ++;
        }
        
    }
    
    for (NSString* str in _arrayPlayerNumber) {
        
        if([str isEqualToString:strCurrentNumber]){
            count ++;
        }else if([str isEqualToString:@"1"] && !_blGuessOne){
            //1 具备万能效果
            count ++;
        }
        
    }
    return count;
}

/**
  对战模式下，开看结果
 */
-(void)openGuessMutilPlay:(whoOpened) wp{
    
    if (!_isShaked && !_isPlayerGuess) return ;//未摇定并且未轮到玩家猜测
    
    
   
    [self hiddenToastView];
    [self stopCountDown];
    if(wp==PlayerOpened){
      [CommonConfigUtil showToast:kToastPositionCenter withTitle:[NSString stringWithFormat:@"%@ 开",_player.playerName]];
    }else{
        [CommonConfigUtil showToast:kToastPositionCenter withTitle:[NSString stringWithFormat:@"%@ 开",_vsPlayer.playerName]];
    }
    
    [self showPhoneDice:(UIImageView*)[self.view viewWithTag:TAG_PhoneDiceBody]];
    
    int count=[self countCurrentGuessNumber];//统计数量
    BOOL playerWin=NO;
    if(count>=_currentGuessAmount){
        if(wp== PlayerOpened){
            playerWin=NO;
        }else{
            playerWin=YES;
        }
    }else{
        if(wp== PlayerOpened){
            playerWin=YES;
        }else{
            playerWin=NO;
        }
    }

    
    if(playerWin){
       
        [self showToastForMatchOpen:1 coins:_chipCoins];

        [_gameClient sendOpenMatch:_player.playerID win:1 vsPlayerId:_vsPlayer.playerID];
    }else{
         [self showToastForMatchOpen:0 coins:_chipCoins];
       [_gameClient sendOpenMatch:_player.playerID win:0 vsPlayerId:_vsPlayer.playerID];
    }
    
    _isPlayerGuess=NO;
    _isShaked=NO;
    [self resetGame];
}
/**
   开骰子
 */
-(void)openGuess:(UIImageView*)diceBodyView{
    if (!_isShaked && !_isPlayerGuess) return ;//未摇定并且未轮到玩家猜测
        
    
    
    [self hiddenToastView];
    [self stopCountDown];
    [CommonConfigUtil showToast:kToastPositionCenter withTitle:@"开！"];

    [self showPhoneDice:diceBodyView];

    int count=[self countCurrentGuessNumber];//统计数量

    int win=0;

    if(count>=_currentGuessAmount){
        
        if(_whoOpened==0 && _whoCurrentGuess==0){
            
            [CommonConfigUtil showToastForNormal:kToastPositionCenter withTitle:[NSString stringWithFormat:@"您赢了,获得%d金币",_chipCoins]];
            _phoneFailureCount++;
            _playerWinCount++;
            win=1;
            
        }else if(_whoOpened==0 && _whoCurrentGuess==1){
            [CommonConfigUtil showToastForNormal:kToastPositionCenter withTitle:[NSString stringWithFormat:@"您输了,减去%d金币",_chipCoins]];
            
            _phoneWinCount++;
            _playerFailureCount++;
            win=0;
            
        }else  if(_whoOpened==1 && _whoCurrentGuess==0){
            [CommonConfigUtil showToastForNormal:kToastPositionCenter withTitle:[NSString stringWithFormat:@"您赢了,获得%d金币",_chipCoins]];
            
            _phoneFailureCount++;
            _playerWinCount++;
            win=1;
            
        }else  if(_whoOpened==1 && _whoCurrentGuess==1){
            [CommonConfigUtil showToastForNormal:kToastPositionCenter withTitle:[NSString stringWithFormat:@"您输了,减去%d金币",_chipCoins]];
            _phoneWinCount++;
            _playerFailureCount++;
            win=0;
        }
    }else{
        if(_whoOpened==0 && _whoCurrentGuess==0){
           [CommonConfigUtil showToastForNormal:kToastPositionCenter withTitle:[NSString stringWithFormat:@"您输了,减去%d金币",_chipCoins]];
            _phoneWinCount++;
            _playerFailureCount++;
            win=0;
           
        }else if(_whoOpened==0 && _whoCurrentGuess==1){
           [CommonConfigUtil showToastForNormal:kToastPositionCenter withTitle:[NSString stringWithFormat:@"您赢了,获得%d金币",_chipCoins]];
            
            _phoneFailureCount++;
            _playerWinCount++;
            win=1;
            
        }else if(_whoOpened==1 && _whoCurrentGuess==0){
           [CommonConfigUtil showToastForNormal:kToastPositionCenter withTitle:[NSString stringWithFormat:@"您输了,减去%d金币",_chipCoins]];
            _phoneWinCount++;
            _playerFailureCount++;
            win=0;
        }else  if(_whoOpened==1 && _whoCurrentGuess==1){
            [CommonConfigUtil showToastForNormal:kToastPositionCenter withTitle:[NSString stringWithFormat:@"您赢了,获得%d金币",_chipCoins]];
            _phoneFailureCount++;
            _playerWinCount++;
            win=1;
        }
    }
    [self calcCoins:win coins:_chipCoins];//计算金币
    
    [self showWinFailtureScorce];
    [self saveWinFailtureScorce];
    
     
       if(win ==1){
         [_gameClient sendGoldCoinCommand:_player coins:_chipCoins tradeType:TradeTypeSinglePlayingWin money:0.0];
       }else {
           [_gameClient sendGoldCoinCommand:_player coins:0-_chipCoins tradeType:TradeTypeSinglePlayingWin  money:0.0];
       }
    
    _isShaked=NO;
    _isPlayerGuess=NO;
     
}
//添加玩家蛊
- (void)addPlayerDiceBody:(float)floatY
{
    float floatViewMiddleX=self.view.frame.size.width /2.0;
    
    int y=floatY - Select_Dice_Height -60;//self.view.frame.size.height - Select_Dice_Height -10;
    
    UIImageView* playDiceBody=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"dicebody.png"]];
    playDiceBody.tag=TAG_PlayerDiceBody;
    playDiceBody.userInteractionEnabled=YES;
    
    //playDiceBody.frame=CGRectMake(floatViewMiddleX- diceBodyWidth/2, y +Desk_Height - diceBodyHeight, diceBodyWidth, diceBodyHeight);
    
      playDiceBody.frame=CGRectMake(floatViewMiddleX- diceBodyWidth/2, y , diceBodyWidth, diceBodyHeight);
    
    UITapGestureRecognizer* tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(startShake: )];
    tapGesture.numberOfTapsRequired=1;
    [playDiceBody addGestureRecognizer:tapGesture];
    [self.view addSubview:playDiceBody];
    
     [self addTouzi:y-50 screenMiddleX:floatViewMiddleX];
    
    _playerGuestView=[[CNGuestView alloc]initWithFrame:CGRectMake(floatViewMiddleX-50, playDiceBody.frame.origin.y -Dice_Height-25, 200, 20)];
    [self.view addSubview:_playerGuestView];
    
    _lblPlayer=[[UILabel alloc]initWithFrame:CGRectMake(floatViewMiddleX-40, playDiceBody.frame.origin.y +diceBodyHeight , 150, 20)];
    _lblPlayer.backgroundColor=[UIColor clearColor];
    [_lblPlayer setTextColor:[UIColor blueColor]];
    
    
    [self.view addSubview:_lblPlayer];
    
    [_playerGuestView showGuessText:@""];
    [_playerGuestView showArrow:NO];
}

/**
 添加玩家双方的盒子
 */
- (void)addPhoneDiceBody:(float)floatViewMiddleX
{
    
    
    UIImageView* phoneDiceBody=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"dicebody.png"]];
    phoneDiceBody.tag=TAG_PhoneDiceBody;
    phoneDiceBody.userInteractionEnabled=YES;
    phoneDiceBody.frame=CGRectMake(floatViewMiddleX- diceBodyWidth/2, _startY, diceBodyWidth-10, diceBodyHeight-10);
    
    UITapGestureRecognizer* tapGesturePhone=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openPhoneDiceBody: )];
    tapGesturePhone.numberOfTapsRequired=1;
    [phoneDiceBody addGestureRecognizer:tapGesturePhone];
    
    [self.view addSubview:phoneDiceBody];

    
      _phoneGuestView=[[CNGuestView alloc]initWithFrame:CGRectMake(floatViewMiddleX-50, phoneDiceBody.frame.origin.y+diceBodyHeight+Dice_Height, 200, 20)];
    [self.view addSubview:_phoneGuestView];
    [_phoneGuestView showGuessText:@""];
    [_phoneGuestView showArrow:NO];
    
    UIImageView* phoneDiceTo=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"diceto.png"]];
     phoneDiceTo.frame=CGRectMake(phoneDiceBody.frame.origin.x + diceBodyWidth +5, _startY+10, 60, 42);
    phoneDiceTo.tag=TAG_PhoneDiceTo;
    phoneDiceTo.hidden=YES;
    [self.view addSubview:phoneDiceTo];
    
    
    
   
    
}
-(void)loadWinFailtureHistroy{
    _userDefaults=[NSUserDefaults standardUserDefaults];
    
    NSString* strPhoneWinCount= [_userDefaults objectForKey:@"PhoneWinCount"];
    NSString* strPhoneFailtureCount= [_userDefaults objectForKey:@"PhoneFailtureCount"];
    
    if(strPhoneFailtureCount!=nil){
        _phoneFailureCount=[strPhoneFailtureCount intValue];
    }else{
        _phoneFailureCount=0;
    }
    if(strPhoneWinCount!=nil){
        _phoneWinCount=[strPhoneWinCount intValue];
    }else{
        _phoneWinCount=0;
    }
    
    
    NSString* strPlayerWinCount= [_userDefaults objectForKey:@"PlayerWinCount"];
    NSString* strPlayerFailtureCount= [_userDefaults objectForKey:@"PlayerFailtureCount"];
    
    if(strPlayerWinCount!=nil){
        _playerWinCount=[strPlayerWinCount intValue];
    }else{
        _playerWinCount=0;
    }
    if(strPlayerFailtureCount!=nil){
        _playerFailureCount=[strPlayerFailtureCount intValue];
    }else{
        _playerFailureCount=0;

    }
    
    

}
//显示输赢分数
-(void)showWinFailtureScorce{
    NSString* vsPlayerName=_vsPlayer==nil?@"手机":_vsPlayer.playerName;
    NSString* playerName=_player==nil?@" 我":_player.playerName;

    _lblShouJi.text=[NSString stringWithFormat:@"%@[胜:%d,负:%d]",vsPlayerName,_phoneWinCount,_phoneFailureCount];
    
   // _lblPlayer.text=[NSString stringWithFormat:@"%@[胜:%d,负:%d]",playerName,_playerWinCount,_playerFailureCount];
    _lblPlayer.text=[NSString stringWithFormat:@"%@[%@ %@金币]",_player.playerName,_player.levelName,_player.coins];
    

}
-(void)saveWinFailtureScorce{
    _userDefaults=[NSUserDefaults standardUserDefaults];
    [_userDefaults setObject:[NSString stringWithFormat:@"%d",_playerFailureCount] forKey:@"PlayerFailtureCount"];
    [_userDefaults setObject:[NSString stringWithFormat:@"%d",_playerWinCount] forKey:@"PlayerWinCount"];
    [_userDefaults setObject:[NSString stringWithFormat:@"%d",_phoneWinCount] forKey:@"PhoneWinCount"];
    [_userDefaults setObject:[NSString stringWithFormat:@"%d",_phoneFailureCount] forKey:@"PhoneFailtureCount"];
    
    [_userDefaults synchronize];
}

-(void)viewDidDisappear:(BOOL)animated{

    //[self saveCurrentPlayerToUserDefaults];
}


-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}
-(void)shareToFriends{
    NSUserDefaults* userDefauls=[NSUserDefaults standardUserDefaults];
    NSString* appUrl=[userDefauls objectForKey:@"appUrl"];
    if(appUrl ==nil || [appUrl isEqualToString:@""]) appUrl=@"http://www.tujiao.com";
    [UMSocialWechatHandler setWXAppId:[CommonConfigUtil getWeiXinAppID] url:appUrl];
    
    [UMSocialQQHandler setQQWithAppId:[CommonConfigUtil getQQAppID] appKey:[CommonConfigUtil getQQAppKey] url:appUrl];
    
    NSString* shareText=@"我再玩[骰子吹牛],等您来挑战!";
    if(_appDelegate.player !=nil && _appDelegate.player.playerName !=nil){
        shareText=[NSString stringWithFormat:@"我是%@,等你来挑战!",_appDelegate.player.playerName];
    }
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:[CommonConfigUtil getUmengAppKey]
                                      shareText:[NSString stringWithFormat: @"%@ 点击下载 %@",shareText,appUrl]
                                     shareImage:[UIImage imageNamed:@"Icon.png"]
                                shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite,UMShareToQQ,UMShareToQzone]
                                       delegate:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _isPlayerGuess=NO;//是否轮到玩家猜测
    _isShaked=NO;// 是否已经摇定骰子
    
    _appDelegate=(CNAppDelegate*)[UIApplication sharedApplication].delegate;
    _gameClient=_appDelegate.gameClient;
    
    _player=[CNGameUtil getCurrentPlayerFromUserDefaults];
    _vsPlayer=_appDelegate.vsPlayer;
    
    _chipCoins=50;//每局50个金币
    
    
    _intBottomSpace=15;
    if(IsIOS7){
        _startY=0;
        
    }

    _userDefaults=[NSUserDefaults standardUserDefaults];
   // UIColor *bgColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"bgImg.png"];
   
    UIColor* bgColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];
    self.view.backgroundColor=bgColor;
    //self.view.backgroundColor=[UIColor purpleColor];
    
 

    [self loadWinFailtureHistroy];
    
   CGRect viewFrame=self.view.frame;
  float floatViewMiddleX=viewFrame.size.width /2.0;
  float floatViewMiddleY=viewFrame.size.height /2.0;
    
    NSString* externAdvType=[_userDefaults objectForKey:@"externAdvType"];
    if(externAdvType==nil) externAdvType=@"0";
    
    if( externAdvType.intValue==0){
        _startY=[self addAlimamaAdv];
    }else if( externAdvType.intValue==1){
        _startY=[self addGoogleAdv];
    }else if( externAdvType.intValue==2){
        _startY=[self addDomonAdv];
    }
    
    //[self addAlimamaHandleView];
    
 _lblTimeCount=[[UILabel alloc]initWithFrame:CGRectMake(viewFrame.size.width /2.0 , floatViewMiddleY -40 , 150, 40)];
    [_lblTimeCount setTextColor:[UIColor whiteColor]];
    _lblTimeCount.backgroundColor=[UIColor clearColor];
    
    [_lblTimeCount setFont:[UIFont fontWithName:@"Arial" size:40.0f]];
    _lblTimeCount.text=@"11";
    _lblTimeCount.hidden=YES;
    [self.view addSubview:_lblTimeCount];
    
    
    
    UIButton* btnHelp=[UIButton buttonWithType:UIButtonTypeCustom];
    
    btnHelp.frame= CGRectMake(10, _startY, 40, 41);
    
    [btnHelp setBackgroundImage:[UIImage imageNamed:@"help.png"] forState:UIControlStateNormal];
    //[btnShare setTitle:@"分享好友..." forState:UIControlStateNormal];
    //btnHelp.titleLabel.font=[UIFont systemFontOfSize:16];
    [btnHelp addTarget:self action:@selector(showHelpView)  forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btnHelp];
    
    
    
    UIButton* btnShare=[UIButton buttonWithType:UIButtonTypeCustom];
    
    btnShare.frame= CGRectMake(self.view.frame.size.width-50, _startY, 40, 41);
    
    [btnShare setBackgroundImage:[UIImage imageNamed:@"share.png"] forState:UIControlStateNormal];
    //[btnShare setTitle:@"分享好友..." forState:UIControlStateNormal];
    //btnShare.titleLabel.font=[UIFont systemFontOfSize:16];
    [btnShare addTarget:self action:@selector(shareToFriends)  forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btnShare];

    
    _lblShouJi=[[UILabel alloc]initWithFrame:CGRectMake(floatViewMiddleX-40, _startY , 150, 20)];
    [_lblShouJi setTextColor:RGB(64,224,208)];
    _lblShouJi.backgroundColor=[UIColor clearColor];

    [self.view addSubview:_lblShouJi];
    
    _startY=_startY+20;

    

    
    
    
    //添加手机的盒子
    [self addPhoneDiceBody:floatViewMiddleX];
    
     //_startY=_startY + background.frame.size.height- diceBodyHeight - Dice_Height ;
    _startY=_startY + Desk_Height- diceBodyHeight - Dice_Height ;
    

    //添加猜测区域UI
     int y=[self addGuessCountUI];

    //添加玩家的蛊
     [self addPlayerDiceBody:y];
    
    
    [self showWinFailtureScorce];
    _timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown:) userInfo:nil repeats:YES];
    [_timer setFireDate:[NSDate distantFuture]];
    

    
}

-(void)readyToPlay{
    //发送准备好开始游戏的命令
    [_gameClient sendReadyPlayCommand:_player vsPlayer:_vsPlayer];
    
  
    
    [self showToastForReadyPlay];
    
}



//倒计时
-(void)countDown:(NSTimer*)timer{
    
    int intCount=_lblTimeCount.text.intValue;
    intCount=intCount-1;
    _lblTimeCount.text=[NSString stringWithFormat:@"%d",intCount];
    
    if (intCount<=0) {
        
        [self stopCountDown];
        [self showPhoneDice:(UIImageView*)[self.view viewWithTag:TAG_PhoneDiceBody]];
        
        _phoneWinCount++;
        _playerFailureCount++;
        [self showWinFailtureScorce];
        [self saveWinFailtureScorce];
        
        [CommonConfigUtil showToast:kToastPositionCenter withTitle:@"超时,您输了!"];
        
        
        [_appDelegate.gameClient sendGuessTimeOver:_player.playerID vsPlayerID:_vsPlayer.playerID chipCoins:_chipCoins];
    }
    
    
}
-(void)addTouzi:(float)diceY screenMiddleX:(float)screenMiddleX{
    int startX=screenMiddleX - Dice_Width * 5 /2;
    
    //逐个添加骰子
      startX =startX  + 5;
    //_startY =_startY + 5;
    
    _image1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1@2x.png"]];
    _image1.frame = CGRectMake(startX, diceY, Dice_Width, Dice_Height);
    [self.view addSubview:_image1];
    
    startX =startX + Dice_Width + 2;
     _image2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"2@2x.png"]];
    _image2.frame = CGRectMake(startX, diceY, Dice_Width, Dice_Height);
    [self.view addSubview:_image2];
    
    startX =startX + Dice_Width + 2;
     _image3 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"3@2x.png"]];
    _image3.frame = CGRectMake(startX, diceY, Dice_Width, Dice_Height);
    [self.view addSubview:_image3];
    
    startX =startX + Dice_Width + 2;
     _image4 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"4@2x.png"]];
    _image4.frame = CGRectMake(startX, diceY, Dice_Width, Dice_Height);
    [self.view addSubview:_image4];
    
    startX =startX + Dice_Width + 2;
     _image5 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"5@2x.png"]];
    _image5.frame = CGRectMake(startX, diceY, Dice_Width, Dice_Height);
    [self.view addSubview:_image5];
    
   
    
    
    
}
-(void)addDongImage{
    NSArray *myImages = [NSArray arrayWithObjects:
                         [UIImage imageNamed:@"dong1@2x.png"],
                         [UIImage imageNamed:@"dong2@2x.png"],
                         [UIImage imageNamed:@"dong3@2x.png"],nil];
    //骰子1的转动图片切换
    _dong1 = [[UIImageView alloc] initWithFrame:_image1.frame];
    
    _dong1.animationImages = myImages;
    _dong1.animationDuration = 0.5;
    [_dong1 startAnimating];
    [self.view addSubview:_dong1];
    
    _dong2 = [[UIImageView alloc] initWithFrame:_image2.frame];
    
    _dong2.animationImages = myImages;
    _dong2.animationDuration = 0.5;
    [_dong2 startAnimating];
    [self.view addSubview:_dong2];
    
    _dong3 = [[UIImageView alloc] initWithFrame:_image3.frame];
    
    _dong3.animationImages = myImages;
    _dong3.animationDuration = 0.5;
    [_dong3 startAnimating];
    [self.view addSubview:_dong3];
    
    
    _dong4 = [[UIImageView alloc] initWithFrame:_image4.frame];
    
    _dong4.animationImages = myImages;
    _dong4.animationDuration = 0.5;
    [_dong4 startAnimating];
    [self.view addSubview:_dong4];
    
    
    _dong5 = [[UIImageView alloc] initWithFrame:_image5.frame];
    
    _dong5.animationImages = myImages;
    _dong5.animationDuration = 0.5;
    [_dong5 startAnimating];
    [self.view addSubview:_dong5];
    
    
    
}
-(void)resetGame{
    isOpened=NO;
    _blHasGuess=NO;
    
 
    _blGuessOne=NO;
    _playerSelectedNumber=1;

    _whoCurrentGuess=0;//当前结果是用户猜测
    _currentGuessAmount=1;// 当前猜测的总数
    _currentGuessNumber=0;//当前猜测的数字
    _phoneGuestView.hidden=YES;
    _playerGuestView.hidden=YES;
    _textFieldCount.text=@" 1";
    _whoOpened=-1;
    _whoCurrentGuess=-1;
    _tableCountNumber.hidden=YES;
    
 
    
  
    
    for (int index=1; index<=6; index++) {
        
        UIImageView* iv=(UIImageView*)[self.view viewWithTag:BaseTag_SelectDice +index];
        [self restoreHighLightImageView:iv];
    }
    
      [self highLightImageView:(UIImageView*)[self.view viewWithTag:(1 +BaseTag_SelectDice)]];

    [self stopCountDown];
}
- (void)startShake:(UIGestureRecognizer*)gesture
{
    if(_isShaked) return ;//已经摇定好
    
    if(_gameStatus== GameStatusPlaying) return;
    
    [self hiddenToastView];
    
    
    UIImageView* diceBodyView=(UIImageView*)[self.view viewWithTag:TAG_PhoneDiceBody];
    
    diceBodyView.image=[UIImage imageNamed:@"dicebody.png"];
    
    UIImageView* diceToView=(UIImageView*)[self.view viewWithTag:TAG_PhoneDiceTo];
    diceToView.image=[UIImage imageNamed:@"diceto.png"];
    diceToView.hidden=YES;
    
    //[self playShakeWav];
    _image1.hidden=YES;
    _image2.hidden=YES;
    _image3.hidden=YES;
    _image4.hidden=YES;
    _image5.hidden=YES;
    
    _dong1.hidden=YES;
    _dong2.hidden=YES;
    _dong3.hidden=YES;
    _dong4.hidden=YES;
    _dong5.hidden=YES;
    
    for(int i=1;i<=5;i++){
        UIImageView* v=(UIImageView*)[self.view viewWithTag:BaseTag_PhoneDice +i];
        if(v !=nil){
           [v removeFromSuperview];
        }
    }
    //******************旋转动画的初始化******************
    //转动骰子的载入
    [self addDongImage];
    
    
    //******************旋转动画******************
    [self addRotateImages];
    
    //摇动盒子
    
    
    [self sharkDiceBody:(UIImageView*)[self.view viewWithTag:TAG_PlayerDiceBody]];
    
    if(self.gameModel==GameModelSinglePlayer){
      [self sharkDiceBody:(UIImageView*)[self.view viewWithTag:TAG_PhoneDiceBody]];
    }

    
    [self resetGame];
    
}
/*
  摇动骰子盒子
 */
-(void)sharkDiceBody:(UIImageView*)sourceView{
    CGPoint p1=  sourceView.center;
    
    CGPoint p2 = CGPointMake(p1.x-30, p1.y);
    
    CGPoint p3 =CGPointMake(p1.x+30, p1.y);
    NSArray *keypoint = [[NSArray alloc] initWithObjects:[NSValue valueWithCGPoint:p1],[NSValue valueWithCGPoint:p2],[NSValue valueWithCGPoint:p1],[NSValue valueWithCGPoint:p3],[NSValue valueWithCGPoint:p1],[NSValue valueWithCGPoint:p2],[NSValue valueWithCGPoint:p1],[NSValue valueWithCGPoint:p3], nil];
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    [animation setValues:keypoint];
    [animation setDuration:4.0];
    [sourceView.layer addAnimation:animation forKey:@"position"];
}

- (BOOL)textFieldCountTouchDown:(UITextField *)textField
{
    [_textFieldCount resignFirstResponder];
    [self showCountTableView];
    return YES;
}

//显示总数选择tableview
-(void)showCountTableView{
    if(_tableCountNumber ==nil){
        
        [self initCountNumberTable:CGRectMake(_viewCount.frame.origin.x, _viewCount.frame.origin.y-150, _viewCount.frame.size.width, 150)];
    }
    
    _tableCountNumber.hidden=NO;

}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return NO;
}

/*添加猜数量的UI
 返回：整个“猜数量”UI区域的宽度
*/
-(float)addGuessCountUI{
    
    int startX=5,guessBarHeight=30;//猜测区高度
    
    float floatViewMiddleX=self.view.frame.size.width /2.0;
    
    float guessButtonHeight=30; //猜测按钮高度
    
    float axisY=self.view.frame.size.height- _intBottomSpace -guessButtonHeight;
    
    UIView* viewPlayerGuess=[[UIView alloc]initWithFrame:CGRectMake(floatViewMiddleX-50, axisY, 102, guessButtonHeight+4)];
    viewPlayerGuess.layer.cornerRadius=5.5;
    viewPlayerGuess.layer.borderWidth=1;
    viewPlayerGuess.backgroundColor=RGB(0,255,0);//RGB(255,69,0);
    viewPlayerGuess.layer.borderColor=RGB(0,255,0).CGColor;
    
    UILabel* lblConfirm=[[UILabel alloc]initWithFrame: CGRectMake(2,2, 98, guessButtonHeight)];
    lblConfirm.font=[UIFont systemFontOfSize:20];
    lblConfirm.textColor=[UIColor purpleColor];
    lblConfirm.text=@"我猜";
    lblConfirm.textAlignment=NSTextAlignmentCenter;
    lblConfirm.userInteractionEnabled=YES;
    [viewPlayerGuess addSubview:lblConfirm];
    [self.view addSubview:viewPlayerGuess];
    
    axisY= axisY - viewPlayerGuess.frame.size.height -5;
    
     _viewCount=[[UIView alloc]initWithFrame:CGRectMake(startX, axisY, 60, guessBarHeight)];
    _viewCount.layer.borderWidth=1;
    _viewCount.layer.cornerRadius=5;
    _viewCount.layer.borderColor=RGB(0,255,0).CGColor;
    [self.view addSubview:_viewCount];
    
   
    _textFieldCount=[[UITextField alloc] initWithFrame:CGRectMake(0, 0, 28, guessBarHeight)];
    [_textFieldCount setBorderStyle:UITextBorderStyleNone];
    _textFieldCount.backgroundColor=[UIColor clearColor];
    _textFieldCount.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
    _textFieldCount.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    _textFieldCount.text=@"  1";
    _textFieldCount.delegate=self;
    [_textFieldCount setTextColor:[UIColor whiteColor]];
    [_textFieldCount addTarget:self action:@selector(textFieldCountTouchDown:) forControlEvents:UIControlEventTouchDown];
  
    [_viewCount addSubview:_textFieldCount];
    

    
    
    UIButton* btnDropUpDown=[UIButton buttonWithType:UIButtonTypeCustom];
    

    
    btnDropUpDown.frame=CGRectMake(_textFieldCount.frame.size.width , 0, 32, 32);
    [btnDropUpDown setImage:[UIImage imageNamed:@"dropdown.png"] forState:UIControlStateNormal];
    [btnDropUpDown addTarget:self action:@selector(showCountTableView) forControlEvents:UIControlEventTouchDown];
    btnDropUpDown.backgroundColor=[UIColor clearColor];
    [_viewCount addSubview:btnDropUpDown];

    startX=startX +_viewCount.frame.size.width +5;
    UILabel* lblGe=[[UILabel alloc]initWithFrame:CGRectMake(startX, axisY, 20, 32)];
    lblGe.backgroundColor=[UIColor clearColor];
    lblGe.text=@"个";
    [lblGe setTextColor:[UIColor whiteColor]];
    [self.view addSubview:lblGe];
    
    
    startX=startX + lblGe.frame.size.width +5;
    for (int index=1; index<=6; index++) {
        UIImageView* iv=[[UIImageView alloc]init];

         iv.image=[UIImage imageNamed:[NSString stringWithFormat:@"%d@2x.png",index]];
        
        
     iv.frame=CGRectMake(startX, axisY, Select_Dice_Width, Select_Dice_Height);
     iv.userInteractionEnabled=YES;
     iv.tag=100 + index;
     UITapGestureRecognizer* tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageViewSelect:)];
     tapGesture.numberOfTapsRequired=1;
     [iv addGestureRecognizer:tapGesture];
    
     [self.view addSubview:iv];
       
        
      startX=startX + 35;
    
    }
    //高亮度第一个骰子
    [self highLightImageView:(UIImageView*)[self.view viewWithTag:(1 + BaseTag_SelectDice)]];
    _playerSelectedNumber=1;
    
    
    UITapGestureRecognizer* tapGeustureConfirm=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playerGuessNumber)];
    tapGeustureConfirm.numberOfTapsRequired=1;
    tapGeustureConfirm.numberOfTouchesRequired=1;
    
    [lblConfirm addGestureRecognizer:tapGeustureConfirm];
   
     
  
    return axisY;// startX + lblGe.frame.size.width;
}
//玩家猜测数字
-(void)playerGuessNumber{
    
    if(!_isShaked){
        
        [CommonConfigUtil showToast:kToastPositionCenter withTitle:@"请摇动手机或轻点蛊开始对战！"];
        return;
    }
     if(!  _isPlayerGuess) return ;//未轮到猜测
    
    if(isOpened) return ;

   
    if(_whoCurrentGuess==0){
        [CommonConfigUtil showToast:kToastPositionCenter withTitle:@"请先等对方猜好！"];
        return;
    }
    
    int count=_textFieldCount.text.intValue;
    
    if(count<_currentGuessAmount){
        //测试的总数不能小于当前数
        [CommonConfigUtil showToast:kToastPositionCenter withTitle:[NSString stringWithFormat:@"不能小于当前个数：%d",_currentGuessAmount]];
        
        return ;
    }
    
    if(count==_currentGuessAmount && _playerSelectedNumber<= _currentGuessNumber){
        
        [CommonConfigUtil showToast:kToastPositionCenter withTitle:[NSString stringWithFormat:@"请选择大于 %d 的骰子！",_currentGuessNumber]];
        return;
    }
    
   // [CommonConfigUtil showToast:kToastPositionCenter withTitle:[NSString stringWithFormat:@"%@：%@个%d",_player.playerName,_textFieldCount.text,_playerSelectedNumber]];
    
    [_playerGuestView showGuessText:[NSString stringWithFormat:@"%@：%@个%d",_player.playerName,_textFieldCount.text,_playerSelectedNumber]];
    _playerGuestView.hidden=NO;
    [_playerGuestView showArrow:YES];
    [_phoneGuestView showArrow:NO];
    
    _currentGuessNumber=_playerSelectedNumber;
    _currentGuessAmount=count;
    
    if(_playerSelectedNumber==1) _blGuessOne=YES;//1 骰子已经使用，不具备万能功能
    
    _whoCurrentGuess=0;//当前结果是用户猜测
    _blHasGuess=YES;
  // 手机计算
  
    if(self.gameModel==GameModelSinglePlayer){
      [NSThread detachNewThreadSelector:@selector(phoneGuessNumber) toTarget:self withObject:nil];
    }
    
    if(self.gameModel == GameModelMutilPlayer){
        [self stopCountDown];
        [_appDelegate.gameClient sendGuessNumber:_player count:count number:_playerSelectedNumber];
        
        [self showToast:tagWaitVSPlayerGuessNumber title:[NSString stringWithFormat:@"请等待[%@]猜测 ",_vsPlayer.playerName] duration:kToastDuration20Second position:kToastPositionCenter];
    }

    
}
// 获得指定数字在数字中得数量
-(int)getNumberCountForArray:(int)num randomArray:(NSArray*) randomArray{
    
    int count=0;//当前猜测数字的数量
    NSString* strCurrentNumber=[NSString stringWithFormat:@"%d",num];
    for (NSString* str in randomArray) {
        
        if([str isEqualToString:strCurrentNumber]){
            count ++;
        }else if([str isEqualToString:@"1"] && !_blGuessOne){
            //1 具备万能效果
            count ++;
        }
        
    }

    return count;
}
//手机猜测
-(void)phoneGuessNumber{
    sleep(1);
        BOOL blFinded=NO;
    int tempCount=[self getNumberCountForArray:_currentGuessNumber randomArray:_arrayPhoneNumber];
    
    if (_currentGuessAmount - tempCount >=4) {
          blFinded=NO;
        
        
    }else{
        
        
        if(_currentGuessAmount<=2){
            //当前猜测总数小于等2，则直接总数递增1
            _currentGuessAmount ++;
            blFinded=YES;
        }else if(_currentGuessAmount<=tempCount || _currentGuessAmount - tempCount==2){//猜测的数量小于等于自己拥有的数量，或者猜测的数量只比自己多1时
            blFinded=YES;

                _currentGuessAmount ++;
        }else{
            
           
            for(int i=_currentGuessNumber +1;i<=6;i++){//从大于当前数开始找到有相同数量的骰子
                tempCount=[self getNumberCountForArray:i randomArray:_arrayPhoneNumber];
                
                if(tempCount >=_currentGuessAmount || _currentGuessAmount - tempCount<=2){
                    _currentGuessNumber =i;
                    blFinded=YES;
                    break;
                }
            }
         if(!blFinded){
            for(int i= 1;i<_currentGuessNumber;i++){
                tempCount=[self getNumberCountForArray:i randomArray:_arrayPhoneNumber];
                
                if(tempCount >=_currentGuessAmount ||  _currentGuessAmount - tempCount<=1){
                     _currentGuessNumber =i;
                     _currentGuessAmount ++;
                    blFinded=YES;
                    break;
                }
                
            }
         }
            
            
            
            
            
        }
        
        
     
    }
    
    if(!blFinded){
        //开 猜测结果
        _whoOpened=1;
        [self openGuess:(UIImageView*)[self.view viewWithTag:TAG_PhoneDiceBody]];
        return;
    }else{
        if(_currentGuessNumber==1) _blGuessOne=YES;//标识 1 已经猜测过
    }
    
   
    //[CommonConfigUtil showToast:kToastPositionCenter withTitle:[NSString stringWithFormat:@"手机：%d个%d",_currentGuessAmount,_currentGuessNumber]];
    
    [_phoneGuestView showGuessText:[NSString stringWithFormat:@"手机：%d个%d",_currentGuessAmount,_currentGuessNumber]];
    
    _phoneGuestView.hidden=NO;
    [_phoneGuestView showArrow:YES];
    [_playerGuestView showArrow:NO];
    _whoCurrentGuess=1;//当前结果是手机猜测
    
     _isPlayerGuess=YES;//轮到玩家猜测
    [self startCountDown];
}
//开始倒计时
-(void)startCountDown{
    _lblTimeCount.text=@"20";
    _lblTimeCount.hidden=NO;
    [_timer setFireDate:[NSDate date]];
}
//停止倒计时
-(void)stopCountDown{
    _lblTimeCount.text=@"20";
    _lblTimeCount.hidden=YES;
    [_timer setFireDate:[NSDate distantFuture]];
}

//高亮度指定的ImageView
-(void)highLightImageView:(UIImageView*) selectedImageView{
    
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame= selectedImageView.frame;
        CGRect newFrame=CGRectMake(frame.origin.x-4, frame.origin.y-4, frame.size.width+4, frame.size.height+4);
        //targetView.frame=newFrame;
        selectedImageView.frame=frame;
        selectedImageView.frame=newFrame;
        selectedImageView.layer.borderWidth=1;
        selectedImageView.layer.borderColor=RGB(0,255,0).CGColor;//[[UIColor whiteColor] CGColor];
        
    }];

}
//将高亮度的imageView回复原样
-(void)restoreHighLightImageView:(UIImageView*) selectedImageView{
    
    if(selectedImageView.frame.size.width==Select_Dice_Width) return;
    
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame= selectedImageView.frame;
        CGRect newFrame=CGRectMake(frame.origin.x+4, frame.origin.y+4, frame.size.width-4, frame.size.height-4);
        selectedImageView.frame=newFrame;
        //selectedImageView.frame=frame;
        //selectedImageView.frame=newFrame;
        selectedImageView.layer.borderWidth=0;
        //selectedImageView.layer.borderColor=[[UIColor whiteColor] CGColor];
        
    }];
    
}

/**
   图片选中事件
 */
-(void)imageViewSelect:(UITapGestureRecognizer*) gesture{
    UIImageView* targetView=(UIImageView*)gesture.view;
    
    int tag=targetView.tag;
    
    int newNum=tag -BaseTag_SelectDice;
    if(newNum == _playerSelectedNumber) return ;
    
    [self highLightImageView:targetView];
    [self restoreHighLightImageView:(UIImageView*)[self.view viewWithTag:(_playerSelectedNumber + BaseTag_SelectDice)]];
    
    _playerSelectedNumber=tag -BaseTag_SelectDice;
    
    /*
    targetView.image=[UIImage imageNamed:[NSString stringWithFormat:@"%d@2x.png",tag  -BaseTag_SelectDice]];
    
    for (int index=1; index<=6; index++) {
        if(tag == BaseTag_SelectDice +index){
            continue;
            
            
        }
        UIImageView* iv=(UIImageView*)[self.view viewWithTag:BaseTag_SelectDice +index];
        
        UIImage* lightImage= [UIImage imageNamed:[NSString stringWithFormat:@"%d@2x.png",index]];
        
        iv.image=[self getGrayImage:lightImage];
    }
*/
    
    
    
 
}
-(void)addRotateImages{
    //设置动画
    CABasicAnimation *spin = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    [spin setToValue:[NSNumber numberWithFloat:M_PI * 16.0]];
    [spin setDuration:4];
    //******************位置变化******************
    //骰子1的位置变化
    CGPoint p1 = CGPointMake(_image1.frame.origin.x, _image1.frame.origin.y);
    CGPoint p2 = CGPointMake(165.0, 100.0);
    CGPoint p3 = CGPointMake(240.0, 160.0);
    CGPoint p4 =p1;// CGPointMake(140.0, 200.0);
    NSArray *keypoint = [[NSArray alloc] initWithObjects:[NSValue valueWithCGPoint:p1],[NSValue valueWithCGPoint:p2],[NSValue valueWithCGPoint:p3],[NSValue valueWithCGPoint:p4], nil];
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    [animation setValues:keypoint];
    [animation setDuration:4.0];
    [animation setDelegate:self];
    
    
    //骰子2的位置变化
    CGPoint p21 = CGPointMake(_image2.frame.origin.x, _image2.frame.origin.y);
    CGPoint p22 = CGPointMake(160.0, 220.0);
    CGPoint p23 = CGPointMake(85.0, 190.0);
    CGPoint p24 =p21;// CGPointMake(140.0, 200.0);
    NSArray *keypoint2 = [[NSArray alloc] initWithObjects:[NSValue valueWithCGPoint:p21],[NSValue valueWithCGPoint:p22],[NSValue valueWithCGPoint:p23],[NSValue valueWithCGPoint:p24], nil];
    CAKeyframeAnimation *animation2 = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    [animation2 setValues:keypoint2];
    [animation2 setDuration:4.0];
    [animation2 setDelegate:self];
    
    
    //骰子3的位置变化
    CGPoint p31 = CGPointMake(_image3.frame.origin.x, _image3.frame.origin.y);
    CGPoint p32 = CGPointMake(175.0, 95.0);
    CGPoint p33 = CGPointMake(140.0, 220.0);
    CGPoint p34 =p31;// CGPointMake(140.0, 200.0);
    NSArray *keypoint3 = [[NSArray alloc] initWithObjects:[NSValue valueWithCGPoint:p31],[NSValue valueWithCGPoint:p32],[NSValue valueWithCGPoint:p33],[NSValue valueWithCGPoint:p34], nil];
    CAKeyframeAnimation *animation3 = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    [animation3 setValues:keypoint3];
    [animation3 setDuration:4.0];
    [animation3 setDelegate:self];
    
    //骰子4的位置变化
    CGPoint p41 = CGPointMake(_image4.frame.origin.x, _image4.frame.origin.y);
    CGPoint p42 = CGPointMake(220.0, 160.0);
    CGPoint p43 = CGPointMake(75.0,  115.0);
    CGPoint p44 =p41;// CGPointMake(140.0, 200.0);
    NSArray *keypoint4 = [[NSArray alloc] initWithObjects:[NSValue valueWithCGPoint:p41],[NSValue valueWithCGPoint:p42],[NSValue valueWithCGPoint:p43],[NSValue valueWithCGPoint:p44], nil];
    CAKeyframeAnimation *animation4 = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    [animation4 setValues:keypoint4];
    [animation4 setDuration:4.0];
    [animation4 setDelegate:self];
    
    
    //骰子5的位置变化
    CGPoint p51 = CGPointMake(_image5.frame.origin.x, _image5.frame.origin.y);
    CGPoint p52 = CGPointMake(225.0, 180.0);
    CGPoint p53 = CGPointMake(195.0, 115.0);
    CGPoint p54 =p51;// CGPointMake(140.0, 200.0);
    NSArray *keypoint5 = [[NSArray alloc] initWithObjects:[NSValue valueWithCGPoint:p51],[NSValue valueWithCGPoint:p52],[NSValue valueWithCGPoint:p53],[NSValue valueWithCGPoint:p54], nil];
    CAKeyframeAnimation *animation5 = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    [animation5 setValues:keypoint5];
    [animation5 setDuration:4.0];
    [animation5 setDelegate:self];
    
    
    //******************动画组合******************
    //骰子1的动画组合
    CAAnimationGroup *animGroup = [CAAnimationGroup animation];
    animGroup.animations = [NSArray arrayWithObjects: animation, spin,nil];
    animGroup.duration = 4;
   // [animGroup setDelegate:self];
    [[_dong1 layer] addAnimation:animGroup forKey:@"position"];
    
    //骰子2的动画组合
    CAAnimationGroup *animGroup2 = [CAAnimationGroup animation];
    animGroup2.animations = [NSArray arrayWithObjects: animation2, spin,nil];
    animGroup2.duration = 4;
   // [animGroup2 setDelegate:self];
    [[_dong2 layer] addAnimation:animGroup2 forKey:@"position"];
    
    //骰子3的动画组合
    CAAnimationGroup *animGroup3 = [CAAnimationGroup animation];
    animGroup3.animations = [NSArray arrayWithObjects: animation3, spin,nil];
    animGroup3.duration = 4;
   // [animGroup3 setDelegate:self];
    [[_dong3 layer] addAnimation:animGroup3 forKey:@"position"];
    //骰子4的动画组合
    CAAnimationGroup *animGroup4 = [CAAnimationGroup animation];
    animGroup4.animations = [NSArray arrayWithObjects: animation4, spin,nil];
    animGroup4.duration = 4;
   // [animGroup4 setDelegate:self];
    [[_dong4 layer] addAnimation:animGroup4 forKey:@"position"];
    //骰子5的动画组合
    CAAnimationGroup *animGroup5 = [CAAnimationGroup animation];
    animGroup5.animations = [NSArray arrayWithObjects: animation5, spin,nil];
    animGroup5.duration = 4;
    [animGroup5 setDelegate:self];
    [[_dong5 layer] addAnimation:animGroup5 forKey:@"position"];
}
-(void)playShakeWav{
    static SystemSoundID soundIDTest = 0;
    NSString * path = [[NSBundle mainBundle] pathForResource:@"yao" ofType:@"wav"];
    
    if (path) {
        
        AudioServicesCreateSystemSoundID( (__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundIDTest );
        
    }
    AudioServicesPlaySystemSound( soundIDTest );
}
-(void)viewDidUnload{
    [_dmAdView removeFromSuperview];
}
/**
   创建多盟广告
 return : 广告高度
 */
-(CGFloat)addDomonAdv{
    
    _dmAdView= [[DMAdView alloc]initWithPublisherId:@"56OJwZS4uNCAJeew/1" placementId:@"16TLua0lApvPkNU0504VkMIz"];
    // 设置广告视图的位置
    _dmAdView.frame = CGRectMake(0, _startY, FLEXIBLE_SIZE.width,
                                 FLEXIBLE_SIZE.height);
    _dmAdView.delegate=self;
    _dmAdView.rootViewController=self;
    [self.view addSubview:_dmAdView];
    [_dmAdView loadAd];
    
    return _startY+ DOMOB_AD_SIZE_320x50.height;
}


- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    
    //停止骰子自身的转动
    [_dong1 stopAnimating];
    [_dong2 stopAnimating];
    [_dong3 stopAnimating];
    [_dong4 stopAnimating];
    [_dong5 stopAnimating];
     //*************产生随机数，真正博饼**************
    srand((unsigned)time(0));  //不加这句每次产生的随机数不变
    //骰子1的结果
    int result1 = (rand() % 6) +1 ;  //产生1～6的数
    switch (result1) {
        case 1:_dong1.image = [UIImage imageNamed:@"1@2x.png"];break;
        case 2:_dong1.image = [UIImage imageNamed:@"2@2x.png"];break;
        case 3:_dong1.image = [UIImage imageNamed:@"3@2x.png"];break;
        case 4:_dong1.image = [UIImage imageNamed:@"4@2x.png"];break;
        case 5:_dong1.image = [UIImage imageNamed:@"5@2x.png"];break;
        case 6:_dong1.image = [UIImage imageNamed:@"6@2x.png"];break;
    }
    //骰子2的结果
    int result2 = (rand() % 6) +1 ;  //产生1～6的数
    switch (result2) {
        case 1:_dong2.image = [UIImage imageNamed:@"1@2x.png"];break;
        case 2:_dong2.image = [UIImage imageNamed:@"2@2x.png"];break;
        case 3:_dong2.image = [UIImage imageNamed:@"3@2x.png"];break;
        case 4:_dong2.image = [UIImage imageNamed:@"4@2x.png"];break;
        case 5:_dong2.image = [UIImage imageNamed:@"5@2x.png"];break;
        case 6:_dong2.image = [UIImage imageNamed:@"6@2x.png"];break;
    }
    //骰子3的结果
    int result3 = (rand() % 6) +1 ;  //产生1～6的数
    switch (result3) {
        case 1:_dong3.image = [UIImage imageNamed:@"1@2x.png"];break;
        case 2:_dong3.image = [UIImage imageNamed:@"2@2x.png"];break;
        case 3:_dong3.image = [UIImage imageNamed:@"3@2x.png"];break;
        case 4:_dong3.image = [UIImage imageNamed:@"4@2x.png"];break;
        case 5:_dong3.image = [UIImage imageNamed:@"5@2x.png"];break;
        case 6:_dong3.image = [UIImage imageNamed:@"6@2x.png"];break;
    }
    //骰子4的结果
    int result4 = (rand() % 6) +1 ;  //产生1～6的数
    switch (result4) {
        case 1:_dong4.image = [UIImage imageNamed:@"1@2x.png"];break;
        case 2:_dong4.image = [UIImage imageNamed:@"2@2x.png"];break;
        case 3:_dong4.image = [UIImage imageNamed:@"3@2x.png"];break;
        case 4:_dong4.image = [UIImage imageNamed:@"4@2x.png"];break;
        case 5:_dong4.image = [UIImage imageNamed:@"5@2x.png"];break;
        case 6:_dong4.image = [UIImage imageNamed:@"6@2x.png"];break;
    }
    //骰子5的结果
    int result5 = (rand() % 6) +1 ;  //产生1～6的数
    switch (result5) {
        case 1:_dong5.image = [UIImage imageNamed:@"1@2x.png"];break;
        case 2:_dong5.image = [UIImage imageNamed:@"2@2x.png"];break;
        case 3:_dong5.image = [UIImage imageNamed:@"3@2x.png"];break;
        case 4:_dong5.image = [UIImage imageNamed:@"4@2x.png"];break;
        case 5:_dong5.image = [UIImage imageNamed:@"5@2x.png"];break;
        case 6:_dong5.image = [UIImage imageNamed:@"6@2x.png"];break;
    }
    
    
    _arrayPlayerNumber=[[NSMutableArray alloc]init];
    [_arrayPlayerNumber addObject:[NSString stringWithFormat:@"%d",result1]];
    [_arrayPlayerNumber addObject:[NSString stringWithFormat:@"%d",result2]];
    [_arrayPlayerNumber addObject:[NSString stringWithFormat:@"%d",result3]];
    [_arrayPlayerNumber addObject:[NSString stringWithFormat:@"%d",result4]];
    [_arrayPlayerNumber addObject:[NSString stringWithFormat:@"%d",result5]];
    
    
    if(self.gameModel==GameModelSinglePlayer){
        //非对战模式，生成手机随机数
      _arrayPhoneNumber=[[NSMutableArray alloc]init];
      [_arrayPhoneNumber addObject:[NSString stringWithFormat:@"%d",(rand() % 6) +1]];
      [_arrayPhoneNumber addObject:[NSString stringWithFormat:@"%d",(rand() % 6) +1]];
      [_arrayPhoneNumber addObject:[NSString stringWithFormat:@"%d",(rand() % 6) +1]];
      [_arrayPhoneNumber addObject:[NSString stringWithFormat:@"%d",(rand() % 6) +1]];
      [_arrayPhoneNumber addObject:[NSString stringWithFormat:@"%d",(rand() % 6) +1]];
    
    }

    
    if(_gameModel==GameModelSinglePlayer) _isPlayerGuess=YES;//轮到玩家猜测
    
    _isShaked=YES;//已经摇定好投资
    
    isOpened=NO;
    
   
    
 
   //
    if(_gameModel== GameModelMutilPlayer){
    //向服务器发送摇动好的骰子点数
      [_appDelegate.gameClient sendDiceNumbers:_player diceNumbers:[NSString stringWithFormat:@"%d,%d,%d,%d,%d",result1,result2,result3,result4,result5]];
    }
}
/**
  将图片变灰
 */
- (UIImage*)getGrayImage:(UIImage*)sourceImage
{
    int width = sourceImage.size.width;
    int height = sourceImage.size.height;
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate (nil,width,height,8,0,colorSpace,kCGImageAlphaNone);
    CGColorSpaceRelease(colorSpace);
    
    if (context == NULL) {
        return nil;
    }
    
    CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage);
    CGImageRef grayImageRef = CGBitmapContextCreateImage(context);
    UIImage *grayImage = [UIImage imageWithCGImage:grayImageRef];
    CGContextRelease(context);
    CGImageRelease(grayImageRef);
    
    return grayImage;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; {
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 20;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _countNumberArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"reuse_themeCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if(cell ==nil){
        cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]   ;

    }
    cell.accessoryType=UITableViewCellAccessoryNone;
    cell.textLabel.text=[_countNumberArray objectAtIndex:indexPath.row];

    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if( _countNumberArray!=nil && _countNumberArray.count>indexPath.row){
       
        _textFieldCount.text=[_countNumberArray objectAtIndex:indexPath.row];
    }
    _tableCountNumber.hidden=YES;
}






-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if([alertView tag]==tagAlertViewUpgrade && buttonIndex == 0) {
        
        NSString *appUrl=  [_userDefaults objectForKey:@"appUrl"];
        if(nil!=appUrl && ![@"" isEqualToString:appUrl]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appUrl]];
        }
        
    }else if(alertView.tag== tagAlertViewRequestPK ){
       if( buttonIndex==0) //接受对战请求
       {

           [self showToastForWaitAcceptPK];
           [_appDelegate.gameClient sendAcceptVSCommand:_player vsPlayerID:_vsPlayer];
          
          
       }else{
           //拒绝对战请求
           [_appDelegate.gameClient sendRejectVSCommand:_player vsPlayerID:_vsPlayer];
       }
    }else if(alertView.tag==tagAlertViewForAcceptPK){
        if( buttonIndex==0) //继续等待对家：接受对战
        {
            [self showToastForWaitAcceptPK];
        }else{
            //不等待
            [self stopWaitVSPlayerResponse];
        }
    }else if(alertView.tag==tagAlertViewWaitVSPlayerSharked){
        if( buttonIndex==0) //继续等待对家：摇定骰子
        {
            [self waitVSPlayerShake];
        }else{
            //不等待
            [self stopWaitVSPlayerResponse];
        }
    }else if (alertView.tag==tagAlertViewWaitVSPlayReady){
        if( buttonIndex==0) //继续等待对家：摇定骰子
        {
            [self showToastForReadyPlay];
        }else{
            //不等待
            [self stopWaitVSPlayerResponse];
        }
    }else if(alertView.tag==tagAlertViewVSPlayOffline){
        //对家已经下线
        if(buttonIndex==0){//选择其他玩家
            [self showOnlinePlayerView];
        }else if(buttonIndex==1){//自己玩
            [self startSinglePlay];
        }
    }
    
}
/**
   显示在线玩家界面
 */
-(void)showOnlinePlayerView{
    
    if (!_appDelegate.gameClient.isConnected) {
        
        [self showToast:-1 title:@"未连接到网络" duration:kToastDurationNormal position:kToastPositionCenter countDown:NO];
    }else{
        
        CNOnlinePlayerController* onlineCtrl=(CNOnlinePlayerController*)[ self.storyboard instantiateViewControllerWithIdentifier:@"CNOnlinePlayerController"];
        
        [self.navigationController pushViewController:onlineCtrl animated:YES];
        //[self presentViewController:navi animated:YES completion:nil];
    }
}
/**
  开启独自玩
 */
-(void)startSinglePlay{
    _appDelegate.gamePlayModel=GameModelSinglePlayer;
    self.gameModel=GameModelSinglePlayer;
    self.gameStatus=GameStatusNormal;
    
    _appDelegate.gameClient.gameMainViewController=self;
    _appDelegate.vsPlayer=nil;
    _vsPlayer=nil;
    _isPlayerGuess=NO;
    _isShaked=NO;
    [self showWinFailtureScorce];
    [self startShake:nil];
    
}
/**
  停止等待对方响应
 */
-(void)stopWaitVSPlayerResponse{
    
}
/**
  显示等待超时信息
 */
-(void)showWaitTimeOverAlertView:(tagAlertView)tag{
    UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:nil message:@"已超时,是否继续等待?" delegate: self cancelButtonTitle:@"继续等待" otherButtonTitles:@"残忍拒绝", nil];

    alertView.tag=tag;
    [alertView show];
    alertView=nil;
}
//toast 倒计时完了
-(void)toastTimeOver:(int)toastTag{
   // NSLog([NSString stringWithFormat:@"%d",toastTag]);
    
    if(toastTag==tagWaitAcceptPK ){
        //接受对战时的提示
        [self showWaitTimeOverAlertView:tagAlertViewForAcceptPK];
        /*
        UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:nil message:@"已超时,是否继续等待?" delegate: self cancelButtonTitle:@"等待" otherButtonTitles:@"残忍拒绝", nil];
      
        alertView.tag=tagAlertViewForAcceptPK;
        [alertView show];
        alertView=nil;*/
    }else if(toastTag==tagWaitStartShark){
        //时间到了,自动摇动骰子
        [self startShake:nil];
    }else if(toastTag== tagWaitVSPlayerSharked){
        
        [self showWaitTimeOverAlertView:tagAlertViewWaitVSPlayerSharked];
        
        /*
        UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:nil message:@"已超时,是否继续等待?" delegate: self cancelButtonTitle:@"等待" otherButtonTitles:@"拒绝", nil];
                alertView.tag=tagAlertViewWaitVSPlayerSharked;
        [alertView show];
        alertView=nil;*/
        
    }else if(toastTag == tagWaitStartGuessNumber){
        
       [self startCountDown];//开始倒计时
    }else if(toastTag == tagWaitVSPlayerGuessNumber){
        //对家猜测超时
        [self showWaitTimeOverAlertView:tagAlertViewWaitVSPlayerSharked];
        
        /*
        UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:nil message:@"已超时,是否继续等待?" delegate: self cancelButtonTitle:@"等待" otherButtonTitles:@"拒绝", nil];
        
        alertView.tag=tagAlertViewWaitVSPlayerSharked;
        [alertView show];
        alertView=nil;*/
    }else  if(toastTag==tagWaitVSPlayReady){
        
        [self showWaitTimeOverAlertView:tagAlertViewWaitVSPlayReady];
        
        
    }

}


//己方猜测超时
-(void)guessNumberTimeOut{
    [self showToast:-1 title:[NSString stringWithFormat: @"您已超时,将扣除%d金币!",_chipCoins ] duration:kToastDuration5Second position:kToastPositionCenter];
    
    [_appDelegate.gameClient sendGuessTimeOver:_player.playerID vsPlayerID:_vsPlayer.playerID chipCoins:_chipCoins];
}
-(void)showToastForReadyPlay{
    [self showToast:tagWaitVSPlayReady title:[NSString stringWithFormat:@"等待[%@]就绪 ",_vsPlayer.playerName] duration:kToastDuration20Second position:kToastPositionCenter];
}
//接收对家请求对战后，显示等待对方响应提示
-(void)showToastForWaitAcceptPK{
    [self showToast:tagWaitAcceptPK title:[NSString stringWithFormat:@"等待对家[%@]响应...",_vsPlayer.playerName] duration:kToastDuration10Second position:kToastPositionCenter];
 
       
    
}
//显示帮助页面
-(void)showHelpView{
    [self dismissViewControllerAnimated:YES completion:nil];
  
}

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    
    if (event.type == UIEventSubtypeMotionShake && _appDelegate.gameStatus==GameStatusNormal)
    {
      
    
        [self startShake:nil];
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
    if(_gameModel== GameModelMutilPlayer){
      [self readyToPlay];
    }
}


- (void)showContentView
{
    if (alimamaHandleView)
    {
        [alimamaHandleView showHandleViewDetailPage];
        badgeView.hidden = YES;
    }
}
- (void)setupSelfDefinedEntrance
{
    UIButton *entranceBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    entranceBtn.frame = CGRectMake(1, CGRectGetMidX(self.view.frame), 100, 37);
    entranceBtn.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    [entranceBtn setTitle:@"精彩推荐" forState:UIControlStateNormal];
    [entranceBtn addTarget:self action:@selector(showContentView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:entranceBtn];
    
    badgeView = [[UMUFPBadgeView alloc] initWithFrame:CGRectMake(entranceBtn.bounds.size.width-18, -3, 22, 22)];
    badgeView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    [entranceBtn addSubview:badgeView];
    badgeView.hidden = YES;
}

//添加阿里妈妈推广墙
-(void)addAlimamaHandleView{
    
    NSString* AliBaBaAdvID=[_userDefaults objectForKey:@"AliBaBaAdvID"];
    
    if(AliBaBaAdvID==nil || [AliBaBaAdvID isEqualToString:@""]) AliBaBaAdvID=@"62918";
    AliBaBaAdvID=@"62918";
    alimamaHandleView = [[UMUFPHandleView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height-88, 32, 88) appKey:nil slotId:AliBaBaAdvID currentViewController:self];
    alimamaHandleView.delegate = (id<UMUFPHandleViewDelegate>)self;
    
    // 集成方式二：入口完全自定义（可以是button，也可以是tableview的cell等），广告未加载完成或加载失败时，点击自定义的入口，广告详情页不会被展示，failedToPackUpHandleView 回调方法被触发
    
    [self setupSelfDefinedEntrance];
    
    [alimamaHandleView requestPromoterDataInBackground];
}
//阿里妈妈广告
-(float)addAlimamaAdv{
 
    CGRect frame=CGRectMake(0, 0,320 ,50);
    
    NSString* AliBaBaAdvID=[_userDefaults objectForKey:@"AliBaBaAdvID"];
 
    if(AliBaBaAdvID==nil || [AliBaBaAdvID isEqualToString:@""]) AliBaBaAdvID=@"62770";
    
    alimamaBanner = [[MMUBannerView alloc] initWithFrame:frame slotId:AliBaBaAdvID currentViewController:self];
 
    alimamaBanner.delegate = (id<MMUBannerViewDelegate>)self;
    //    [MMUBannerView setAppChannel:@"App Store"];
    [self.view addSubview:alimamaBanner];
    [alimamaBanner requestPromoterDataInBackground];
    return alimamaBanner.frame.size.height;
}
-(float)addGoogleAdv{
    bannerView_ = [[GADBannerView alloc]
                   initWithFrame:CGRectMake(0.0,
                                            0.0 ,
                                            GAD_SIZE_320x50.width,
                                            GAD_SIZE_320x50.height)];    // 指定广告单元ID。
    
    bannerView_.adUnitID = [CommonConfigUtil getGoogleAdvId];
    
    bannerView_.rootViewController = self;
    [self.view addSubview:bannerView_];
    GADRequest *request = [GADRequest request];
    // request.testDevices = @[ GAD_SIMULATOR_ID ];
    [bannerView_ loadRequest:request];
    
    return bannerView_.frame.size.height;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self resignFirstResponder];
    [super viewWillDisappear:animated];
}
-(BOOL)canBecomeFirstResponder{
    return YES;
}


//开始摇动
-(void) startShakeDiceInMutilPlayer{
  
    [self showToast:tagWaitStartShark title:@"请摇动手机或轻点蛊开始对战!" duration:kToastDuration5Second position:kToastPositionCenter];
    

}




-(void)hiddenToastView{
    if(toast !=nil){
        [toast hideToast:nil];
        toast=nil;
    }
    
}
-(void)showToast:(int)tag title:(NSString*)title duration:(ToastDuration)duration position:(ToastPosition)position{
    [self showToast:tag title:title duration:duration position:position countDown:YES];
}
-(void)showToast:(int)tag title:(NSString*)title duration:(ToastDuration)duration position:(ToastPosition)position countDown:(BOOL)countDown{
    
    [self hiddenToastView];
    toast = [iToast makeToast:title];
    toast.tag=tag;
    toast.toastDelegate=self;
    toast.countDown=countDown;
    [toast setToastPosition:position];
    [toast setToastDuration:duration];
    [toast show];
}

-(void)dealloc{
    bannerView_=nil;
    _dmAdView.rootViewController=nil;
    _dmAdView.delegate=nil;
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Game Client Protocol
//等待对家摇定骰子
-(void) waitVSPlayerShake{
    [self showToast:tagWaitVSPlayerSharked title:[NSString stringWithFormat:@"等待[%@]摇定骰子 ",_vsPlayer.playerName] duration:kToastDuration20Second position:kToastPositionCenter];
}
//对家已经下线
-(void)vsPlayerOffline{
    
    
    UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:@"玩家[%@]已经下线",_appDelegate.vsPlayer.playerName] delegate: self cancelButtonTitle:@"与其他玩家对战" otherButtonTitles:@"自己玩", nil];
    // alertView.alertViewStyle=UIAlertViewStylePlainTextInput;
    alertView.tag=tagAlertViewVSPlayOffline;
    [alertView show];
    alertView=nil;
}
/**
 有玩家邀请对战
 */
-(void) requestPK:(CNPlayer*)vsPlayer{
    if(isPlayingVS){
        //正在对战中
        [_appDelegate.gameClient sendRejectVSCommand:_player vsPlayerID:vsPlayer ];
    }else{
        _vsPlayer=vsPlayer;
        UIAlertView* alertView=[[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:@"玩家[%@]想和您对战，是否接受?",vsPlayer.playerName] delegate: self cancelButtonTitle:@"接受" otherButtonTitles:@"残忍拒绝", nil];
        // alertView.alertViewStyle=UIAlertViewStylePlainTextInput;
        alertView.tag=tagAlertViewRequestPK;
        [alertView show];
        alertView=nil;
    }
}
//设定对家摇定所有骰子点数
-(void) setVSPlayerAllDiceNumbers:(NSMutableArray*) arrayNumbers{
   // [self hiddenToastView];
    _arrayPhoneNumber=arrayNumbers;
    
    //摇动对家的蛊
   // [self sharkDiceBody:(UIImageView*)[self.view viewWithTag:TAG_PhoneDiceBody]];
    
}
//等待对方猜测
-(void)waitVSPlayerGuess{
    [self showToast:tagWaitVSPlayerGuessNumber title:@"请等待对家猜测!" duration:kToastDuration20Second position:kToastPositionCenter];
}
//开始猜测
-(void)startGuessNumber{
    _isPlayerGuess=YES;
    [self showToast:tagWaitStartGuessNumber title:@"请猜测!" duration:kToastDurationShort position:kToastPositionCenter];
}

//对家猜测数据
-(void)setVSPlayerGuessData:(NSString*)vsPlayerId count:(int) count number:(int)number{
    
    
    [self hiddenToastView];
    
    _currentGuessAmount=count;
    _currentGuessNumber=number;
    
    [CommonConfigUtil showToast:kToastPositionCenter withTitle:[NSString stringWithFormat:@"%@：%d个%d",_vsPlayer.playerName,_currentGuessAmount,_currentGuessNumber]];
    
    [_phoneGuestView showGuessText:[NSString stringWithFormat:@"%@：%d个%d",_vsPlayer.playerName,_currentGuessAmount,_currentGuessNumber]];
    
    
    _phoneGuestView.hidden=NO;
    [_phoneGuestView showArrow:YES];
    [_playerGuestView showArrow:NO];
    _whoCurrentGuess=1;//当前结果是手机猜测
    
    _isPlayerGuess=YES;
    [self startCountDown];
}
//设置比赛结果
-(void)setMatchResult:(int)win coins:(int)coins{
    
    
    [self hiddenToastView];
    [self stopCountDown];
 
    [self resetGame];
    [CommonConfigUtil showToast:kToastPositionCenter withTitle:[NSString stringWithFormat:@"%@ 开",_vsPlayer.playerName]];
  
    
    
    [self showPhoneDice:(UIImageView*)[self.view viewWithTag:TAG_PhoneDiceBody]];
    
    [self showToastForMatchOpen:win coins:_chipCoins];
    
    [self calcCoins:win coins:coins];//计算金币
    
    _isShaked=NO;
    _isPlayerGuess=NO;
   
}

/**
   计算玩家金币
  win :1 获胜,0 负
 
 */
-(void)calcCoins:(int)win coins:(double)coins{
    
    double c=_player.coins.doubleValue;
    
    if(win==1){
        //胜
        c=c + coins;
    }else{
        //负
        c=c - coins;
    }
    _player.coins=[NSString stringWithFormat:@"%f",c];
    
   _player.levelName= [CNGameUtil calcPlayerLevelName:c];//计算等级
    [CNGameUtil saveCurrentPlayerToUserDefaults:_player];
    [self showWinFailtureScorce];
}
-(void)showToastForMatchOpen:(int)win coins:(int)coins{
    if(win==1){
        //获胜
        [self showToast:-1 title:[NSString stringWithFormat:@"您赢了,获得金币:%d! 摇动手机或轻点蛊开始下一局",coins ] duration:kToastDurationNormal position:kToastPositionCenter countDown:NO];
    }else{
        //负
        [self showToast:-1 title:[NSString stringWithFormat:@"您输了,扣除金币:%d! 摇动手机或轻点蛊开始下一局",coins ] duration:kToastDurationNormal position:kToastPositionCenter countDown:NO];
    }
}

@end
